<template>
    <div class="ct-bodySet">
        <el-container>
            <el-header class="bgclr-dk-sp0 mb20 headerCoster" >
                <el-breadcrumb separator-class="el-icon-arrow-right">
                    <el-breadcrumb-item :to="{ path: '/mainPage/welcome' }">首页</el-breadcrumb-item>
                    <el-breadcrumb-item>系统管理</el-breadcrumb-item>
                    <el-breadcrumb-item><span class="main-Clr-ft">小组管理</span></el-breadcrumb-item>
                </el-breadcrumb>
            </el-header>
            <el-container class="pl20 pr20" style="display: flex">
                <el-card class="mr15 cardMinWidth autoHeight">
                    <div slot="header">
                        <span>小组列表</span>
                    </div>
                    <el-tree :data="groupTreeData"
                             ref="groupTreeData"
                             :props="groupTreeDataProps"
                             default-expand-all
                             :expand-on-click-node="false"
                             :highlight-current="true"
                             node-key="id"
                             @node-click="clickNode">
                        <span slot-scope="{ node, data }">
<!--                            <span v-if="data.id==''" class="labelstyleTree tx-Elps main-Clr-ft" :title="node.label" >{{ node.label }}</span>-->
                            <span  class="labelstyleTree tx-Elps" :title="node.label" >{{ node.label }}</span>
                            <span>
                                <span v-if="data.children">
                                    <i title="添加" class="iconfont icon-tianjia ml2 mr2 main-Clr-ft" @click.stop="addNode(data)"></i>
                                    <i title="删除" class="iconfont icon-shanchu main-Clr-ft" v-if="data.children.length<1" @click.stop="() => deleteNode(node, data)"></i>
                                </span>
                                <span v-else>
                                    <i title="取消添加" class="iconfont icon-shanchu ml2 mr2 main-Clr-ft" @click.stop="cancel(node, data)"></i>
                                </span>
                            </span>
                        </span>
                    </el-tree>
                </el-card>

                <el-card class="autoHeight cardWidth" v-show="showFlag" style="flex:1">
                    <div slot="header">
                        <span v-if="flage">
                            <span>新建</span>
                            <span class="main-Clr-ft ml2 mr2">{{patientRole.groupName}}</span>
                            <span>的下属组</span>
                        </span>
                        <span v-else>
                            当前编辑组
                            <span class="main-Clr-ft ml2" >{{comparFormValue.groupName}}</span>
                        </span>
                    </div>
                    <el-form
                            :model="inpFormValue"
                            ref="inpFormValue"
                            :rules="formRules">

                        <el-form-item label="组名称:" prop="groupName" label-width="19%">
                            <el-input v-model.trim="inpFormValue.groupName" placeholder="请输入组名称" size="small" id="groupNameID" class="inputWidth" maxlength="225"></el-input>
                        </el-form-item>

                        <el-form-item label="父组:" label-width="19%">
                            {{inpFormValue.parentName}}
                        </el-form-item>

                        <el-form-item label="写周报标记:" prop="weekFlag" label-width="19%" >
                            <el-switch
                                    v-model="inpFormValue.weekFlag"
                                    active-text="是"
                                    inactive-text="否">
                            </el-switch>
                        </el-form-item>

                        <el-form-item label="组说明:" prop="description" label-width="19%" class="mb10">
                            <el-input placeholder="请输入组说明" type="textarea" :autosize="{minRows: 4, maxRows: 6}" v-model.trim="inpFormValue.description" maxlength="100" class="inputWidth"></el-input>
                            <div class="textAlignRight clr-dk-sp5 countNumber">{{inpFormValue.description.length}}/100</div>
                        </el-form-item>

                        <el-form-item>
                            <el-button type="primary" @click="submitForm('inpFormValue')" size="small" class="submitButton">提交</el-button>
                            <el-button v-if="flage" class="bkmgColor" @click="resetForm('inpFormValue')" size="small">重置</el-button>
                        </el-form-item>
                    </el-form>
                </el-card>
            </el-container>
            <div class="bottomLayoutBus"></div>
        </el-container>
    </div>
</template>

<script>
    import urlConfig from '../../../config/url.json';
    import Vue from 'vue';
    import { Message } from 'element-ui';

    Vue.component(Message.name, Message);

    let myUrl = urlConfig.groupManage;
    let getUrl = urlConfig.groupById;
    export default {
        data(){
            return{
                compareFlag:true,                       //新旧值对比标识,true代表相同
                showFlag:false,
                selectFlag:true,
                flage:false,                            //标记是否添加
                groupTreeData : [],
                groupTreeDataProps:{
                    children: 'children',
                    label: 'groupName',
                },
                inpFormValue : {            //表单
                    "id":'',
                    "groupName":"",
                    "parentId":'',
                    "parentName":"",
                    "weekFlag":'',
                    "description":"",
                    "createBy":'',
                    "createDate":'',
                    "updateBy":'',
                    "updateDate":'',
                    children:[]
                },
                comparFormValue : {},//比较用数据
                patientRole : {},//新添加角色的父角色
                formRules: {
                    groupName: [
                        { required: true,message:'必填信息',trigger: 'blur' },        //required   是否必填
                        { max: 255, message: '最长255个字符', trigger: 'blur' }
                    ],

                },
            }
        },
        methods:{
            //获取树的数据
            getTreeData(){
                debugger;
                let that=this;
                const loading = this.$loading({
                    lock: true,
                    text: 'Loading',
                    spinner: 'el-icon-loading',
                });
                that.$http({
                    method: 'get',
                    url: myUrl,
                    baseURL:'/api'
                }).then(function(response){
                    if(response.data.code==200) {
                        var newdata=response.data.data.groupInfo;
                        that.groupTreeData=that.getJsonTree(newdata,'-1');
                    }else{
                        Message.error('获取小组树失败');
                    }
                    loading.close();
                }).catch(function(err){
                    console.log(err);
                    Message.error('获取小组树失败');
                    loading.close();
                });
            },

            getJsonTree(newdata,parentId){
                let that=this;
                var itemArr=[];
                for(var i=0;i<newdata.length;i++){
                    var node=newdata[i];
                    if(node.parentId==parentId ){
                        var newNode={id:node.id,
                            groupName:node.groupName,
                            parentId:node.parentId,
                            description:node.description,
                            weekFlag:node.weekFlag,
                            createBy:node.createBy,
                            createDate:node.createDate,
                            updateBy:node.updateBy,
                            updateDate:node.updateDate,
                            children:that.getJsonTree(newdata,node.id)};
                        itemArr.push(newNode);
                    }
                }
                return itemArr;
            },

            //新旧值对比
            compareData(){
                let that=this;
                if(that.showFlag==false){
                    that.compareFlag = true;
                }
                else if(that.inpFormValue.groupName!==that.comparFormValue.groupName||that.inpFormValue.description!==that.comparFormValue.description||that.inpFormValue.weekFlag!==that.comparFormValue.weekFlag){
                    that.compareFlag=false;
                }else{
                    that.compareFlag=true;
                }
            },

            //获取树节点数据
            getData(id){
                let that = this;
                this.$refs['inpFormValue'].clearValidate();

                const loading = this.$loading({
                    lock: true,
                    text: 'Loading',
                    spinner: 'el-icon-loading',
                });
                this.$http({
                    method: 'get',
                    url: getUrl,
                    baseURL:'/api',
                    params: {
                        id : id
                    }
                }).then(function(response){
                    if(response.data.code=200) {
                        debugger
                        that.inpFormValue= response.data.data;
                        that.showFlag = true;
                        //对比新旧值用
                        that.comparFormValue.id= response.data.data.id;
                        that.comparFormValue.groupName= response.data.data.groupName;
                        that.comparFormValue.description= response.data.data.description;
                        if(response.data.data.weekFlag==1){
                            that.comparFormValue.weekFlag=true;
                            that.inpFormValue.weekFlag=true;
                        }else{
                            that.comparFormValue.weekFlag=false;
                            that.inpFormValue.weekFlag=false;
                        }
                    }else{
                        Message.error('获取组信息失败');
                    }
                    loading.close();
                }).catch(function(err){
                    console.log(err);
                    Message.error('获取小组失败');
                    loading.close();
                });
            },

            //点击树节点-->获取组信息
            clickNode(data){
                let that = this;
                that.compareData();

                if(that.flage){
                    Message.warning('请先完成本次添加')
                }else if(!that.compareFlag){
                    this.$confirm('是否取消当前操作', '提示', {
                        confirmButtonText: '是',
                        cancelButtonText: '否',
                        type: 'warning'
                    }).then(() => {
                        that.$refs['inpFormValue'].clearValidate();
                        that.$refs.groupTreeData.setCurrentKey(that.comparFormValue.id);
                        that.getData(that.inpFormValue.id);
                        Message.info('操作已取消');
                        that.compareFlag=true;
                    }).catch(() => {
                        this.$refs.groupTreeData.setCurrentKey(that.comparFormValue.id);
                        Message.info('请继续操作');
                    });
                }else{
                    that.getData(data.id);
                }
            },

            //添加节点
            addData(data){
                debugger;
                let that=this;
                this.$refs['inpFormValue'].clearValidate();
                const newChild = { id: '', groupName: '新角色',parentId :data.id,parentName:data.groupName,description:'',weekFlag:false,createBy:'',createDate:'',updateBy:'',updateDate:'' };
                if (!data.children) {
                    this.$set(data, 'children', []);
                }
                data.children.push(newChild);
                that.inpFormValue=newChild;
                that.flage=true;
                that.patientRole=data;
                that.showFlag = true;

            },

            //点击'添加'按钮-->添加节点
            addNode(data){
                let that = this;
                that.compareData();
                if(that.flage){
                    Message.warning('请先完成上次添加')
                }else if(!that.compareFlag){
                    this.$confirm('是否取消当前操作', '提示', {
                        confirmButtonText: '是',
                        cancelButtonText: '否',
                        type: 'warning'
                    }).then(() => {
                        that.$refs['inpFormValue'].clearValidate();
                        that.$refs.groupTreeData.setCurrentKey(that.comparFormValue.id);
                        that.getData(that.comparFormValue.id);
                        Message.info('操作已取消');
                        that.compareFlag=true;
                    }).catch(() => {
                        this.$refs.groupTreeData.setCurrentKey(that.comparFormValue.id);
                        Message.info('请继续操作');
                    });
                }else{
                    this.$refs.groupTreeData.setCurrentKey(data.id);
                    that.addData(data);
                }
            },

            //取消添加
            cancel(node, data){
                let that=this;
                this.$confirm('是否取消当前操作?', '警告', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    const parent = node.parent;
                    const children = parent.data.children || parent.data;
                    const index = children.findIndex(d => d.id === data.id);
                    children.splice(index, 1);
                    that.flage=false;
                    Message.info('操作已取消');
                    // this.$refs.groupTreeData.setCurrentKey(data.id);
                    that.getData(that.comparFormValue.id);
                }).catch(() => {
                    Message.info('请继续操作');
                });
            },

            //删除节点
            deleteData(data){
                let that=this;
                this.$confirm('确定要删除    <span class="main-Clr-ft">'+ data.groupName   +'</span>    吗？','温馨提示',{
                    dangerouslyUseHTMLString: true,
                    confirmButtonText:'确定',
                    cancelButtonText:'取消',
                    type:'warning'
                }).then(() => {
                    const loading = this.$loading({
                        lock: true,
                        text: 'Loading',
                        spinner: 'el-icon-loading',
                    });
                    this.$http({
                        method: 'delete',
                        url: myUrl,
                        baseURL:'/api',
                        data:{
                            "id":data.id,
                        }
                    }).then(function(response){
                        if(response.data.code==200) {
                            Message.success('删除成功');
                            that.showFlag=false;
                            that.getTreeData();
                        }else{
                            Message.error('删除失败');
                        }
                        loading.close();
                    }).catch(function(err){
                        Message.error('删除失败');
                        console.log(err);
                        loading.close();
                    });
                }).catch(() => {
                    Message.info('已取消删除');
                });
            },

            //点击'删除'按钮-->删除节点
            deleteNode(node, data){
                debugger;
                let that = this;
                that.compareData();
                if(that.flage){
                    Message.warning('请先完成本次添加');
                }else if(!that.compareFlag){
                    this.$confirm('是否删除当前新增节点操作', '提示', {
                        confirmButtonText: '是',
                        cancelButtonText: '否',
                        type: 'warning'
                    }).then(() => {
                        that.$refs['inpFormValue'].clearValidate();
                        that.$refs.groupTreeData.setCurrentKey(that.comparFormValue.id);
                        that.getTreeData();
                        Message.info('操作已取消');
                        that.compareFlag=true;
                        that.showFlag = false;
                    }).catch(() => {
                        this.$refs.groupTreeData.setCurrentKey(that.comparFormValue.id);
                        Message.info('请继续操作');
                    });
                }else{
                    this.$refs.groupTreeData.setCurrentKey(data.id);
                    that.deleteData(data);
                }
            },

            //添加和修改的提交
            submitForm(formName){
                let that=this;
                let weekFlagNum;
                debugger;
                if(that.inpFormValue.weekFlag==true){
                    weekFlagNum=1;
                }else{
                    weekFlagNum=0;
                }
                var method = (that.flage? "post":"put");
                that.$refs[formName].validate((valid) => {
                    if (valid) {
                        const loading = this.$loading({
                            lock: true,
                            text: 'Loading',
                            spinner: 'el-icon-loading',
                        });
                        this.$http({
                            method: method,
                            url: myUrl,
                            baseURL:'/api',
                            data:{
                                'id':that.inpFormValue.id,
                                'groupName':that.inpFormValue.groupName,
                                'parentId':that.inpFormValue.parentId,
                                'description':that.inpFormValue.description,
                                'weekFlag':weekFlagNum
                            }
                        }).then(function(response){
                            if(response.data.code==200) {
                                if(method=="post"){
                                    that.inpFormValue.id = response.data.data.id;
                                }
                                that.comparFormValue.groupName=that.inpFormValue.groupName;
                                that.comparFormValue.description=that.inpFormValue.description;
                                that.comparFormValue.weekFlag=that.inpFormValue.weekFlag;
                                Message.success('操作成功');
                                that.getTreeData();
                            }else{
                                Message.error('操作失败');
                                console.log('!199-400');
                                console.log(response);
                            }
                            that.flage=false;
                            loading.close();
                        }).catch(function(err){
                            Message.error('操作失败');
                            console.log(err);
                            that.flage=false;
                            that.getTreeData();
                            loading.close();
                        });
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            },

            //重置
            resetForm(formName) {
                this.$refs[formName].resetFields();
            },

        },
        mounted(){
            let that = this;
            that.getTreeData();

        },
        updated(){
            let that=this;
            if(this.selectFlag){
                //1页面加载完成左侧树默认选中
                // this.$refs.groupTreeData.setCurrentKey(that.defaultId);
                this.selectFlag=false;
            }

        }
    }
</script>

<style scoped>
    .inputWidth{
        width: 77%;
    }

    .headerCoster{
        height: 59px;
        border-top: 1px solid #eee;
        border-bottom: 1px solid #eee;
    }

    /*计数*/
    .countNumber{
        margin-right: 23%;
    }

    .submitButton{
        margin-left: 19%;
    }

    /*.roleCardHight {*/
    /*height: 611px;*/
    /*}*/

    .cardMinWidth{
        min-width: 275px;
    }

    .cardWidth{
        width: 100%;
    }
</style>